package com.srwl.mytx.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.srwl.mytx.Constant;
import com.srwl.mytx.dao.DBManager;
import com.srwl.mytx.domain.Message;
import com.srwl.mytx.domain.User;
import com.srwl.mytx.R;
import com.srwl.mytx.RetrofitManager;
import com.srwl.mytx.domain.CommonResult;
import com.srwl.mytx.domain.Topic;
import com.srwl.mytx.im.IMSClientBootstrap;
import com.srwl.mytx.im.conversation.Conversation;
import com.srwl.mytx.im.conversation.SystemNotifyConversation;
import com.srwl.mytx.parse.UserProfileManager;
import com.srwl.mytx.service.TopicService;
import com.srwl.mytx.service.UserService;
import com.srwl.mytx.utils.GlideLoadUtils;

import butterknife.BindView;
import butterknife.ButterKnife;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 主题审核页面
 */
public class VerifyTopicActivity extends BaseActivity {
    public static void startActivity(Context context, Message notify) {
        context.startActivity(new Intent(context, VerifyTopicActivity.class).putExtra(Constant.EXTRA_INFO_MESSAGE, notify));
    }

    private static final String TAG = "VerifyTopicActivity";
    @BindView(R.id.tv_topic_title)
    TextView tv_topicTitle;
    @BindView(R.id.tv_topic_status)
    TextView tv_topicStatus;
    @BindView(R.id.iv_avatar)
    ImageView iv_avatar;
    @BindView(R.id.tv_username)
    TextView tv_username;
    @BindView(R.id.et_reason)
    EditText et_reason;
    @BindView(R.id.tv_reason)
    TextView tv_reason;
    @BindView(R.id.btn_agree)
    Button btn_agree;
    @BindView(R.id.btn_refuse)
    Button btn_refuse;
    @BindView(R.id.progress_bar)
    ProgressBar progressBar;

    @BindView(R.id.ll_user_info)
    LinearLayout ll_userInfo;
    @BindView(R.id.rl_target_user_info)
    RelativeLayout rl_userInfo;

    @BindView(R.id.ll_reason)
    LinearLayout ll_reason;

    @BindView(R.id.driver1)
    View driver1;
    @BindView(R.id.tv_customer_service)
    TextView tv_customerService;
    @BindView(R.id.driver_2)
    View driver2;

    private Message notify;
    private Topic topic;
    private boolean isTopicManger; //主题创建者

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (savedInstanceState != null) {
            finish();
        }
        setContentView(R.layout.activity_verify_topic);
        ButterKnife.bind(this);

         notify = getIntent().getParcelableExtra(Constant.EXTRA_INFO_MESSAGE);
        if (notify != null) {
            topic = JSONObject.parseObject(notify.getExtraData(), Topic.class);
        }
        if (topic == null) {
            Log.e(TAG, "onCreate: 主题不能为空");
            return;
        }
        tv_topicTitle.setText(topic.getTitle());

        User manager = topic.getManager();

        if (manager != null) {
            isTopicManger = UserProfileManager.getInstance().getLoginUserInfo().getuId().equals(manager.getuId());
        } else {
            isTopicManger = true;//在通知消息中，没回传 主题创建者的时候，说明是发给主题创建者的
        }

        if (isTopicManger) { //主题创建者看到的页面，
            ll_userInfo.setVisibility(View.GONE);
            rl_userInfo.setVisibility(View.GONE);
            showCustomerService();
        } else { //主题审核者 看到的页面
            hideCustomerService();
            if (manager != null) {
                GlideLoadUtils.glideLoad(this, manager.getAvatar(), iv_avatar);
                tv_username.setText(manager.getUsername());
                rl_userInfo.setOnClickListener(v -> startActivity(new Intent(this, ChatActivity.class).putExtra(Constant.EXTRA_TARGET_USER_INFO, manager)));
            }
        }
        showTopicStatus();
        if (topic.getExtra() != null) {
            tv_reason.setText(topic.getExtra());
        } else {
            ll_reason.setVisibility(View.GONE);
        }

        tv_topicTitle.setOnClickListener(v -> startActivity(new Intent(this, TopicDetailsActivity.class).putExtra(Constant.EXTRA_INFO_TOPIC, topic)));
    }

    private void showCustomerService() {
        driver1.setVisibility(View.VISIBLE);
        driver2.setVisibility(View.VISIBLE);
        tv_customerService.setVisibility(View.VISIBLE);
        tv_customerService.setOnClickListener(v -> contactCustomerService());

    }

    private void hideCustomerService() {
        driver1.setVisibility(View.GONE);
        driver2.setVisibility(View.GONE);
        tv_customerService.setVisibility(View.GONE);
    }

    private void showTopicStatus() {
        String statusDescribe;
        Integer status = topic.getStatus();
        if (status == Constant.TOPIC_STATUS_WAIT_VERIFY) {
            statusDescribe = "等待审核";
            btn_agree.setOnClickListener(v -> agree());
            btn_refuse.setOnClickListener(v -> refuse());
        } else if (status == Constant.TOPIC_STATUS_NORMAL) {
            statusDescribe = "审核通过";
            btn_agree.setVisibility(View.GONE);
            btn_refuse.setVisibility(View.GONE);
            et_reason.setVisibility(View.GONE);
            tv_reason.setVisibility(View.VISIBLE);

        } else {
            statusDescribe = "审核未通过";
            if (isTopicManger) {
                btn_refuse.setText("重新编辑提交");
                btn_refuse.setOnClickListener(v -> toEditTopic());
            } else {
                btn_refuse.setVisibility(View.GONE);
            }
            btn_agree.setVisibility(View.GONE);
            et_reason.setVisibility(View.GONE);
            tv_reason.setVisibility(View.VISIBLE);
        }
        tv_topicStatus.setText(statusDescribe);
    }

    private void toEditTopic() {
        EditTopicActivity.startActivity(this, topic);
    }


    private void agree() {

        RetrofitManager.getInstance().createRequest(TopicService.class)
                .verifySuccess(topic.getId())
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        progressBar.setVisibility(View.GONE);
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "onResponse: " + response.message());
                            showToast(btn_agree, getString(R.string.system_busy));
                            return;
                        }
                        if (result.isError()) {
                            Log.e(TAG, "onResponse: " + result.getMsg());
                            showToast(btn_agree, result.getMsg());
                            return;
                        }
                        showToast(btn_agree, "通过操作已经完成");
                        topic.setStatus(Constant.TOPIC_STATUS_NORMAL);
                        showTopicStatus();
                        //setResult(RESULT_OK, new Intent().putExtra(Constant.EXTRA_INFO_TOPIC, topic));
                        onTopicDataChange();
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        Log.e(TAG, "onFailure: " + t.getMessage());
                    }
                });

    }


    private void refuse() {
        Topic newTopic = new Topic();
        newTopic.setId(topic.getId());
        String reason = et_reason.getText().toString();
        newTopic.setExtra(reason);
        RetrofitManager.getInstance().createRequest(TopicService.class)
                .verifyFail(newTopic)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        progressBar.setVisibility(View.GONE);
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "onResponse: " + response.message());
                            showToast(btn_agree, getString(R.string.system_busy));
                            return;
                        }
                        if (result.isError()) {
                            Log.e(TAG, "onResponse: " + result.getMsg());
                            showToast(btn_agree, result.getMsg());
                            return;
                        }
                        showToast(btn_agree, "拒绝通过操作已经完成");
                        topic.setStatus(Constant.TOPIC_STATUS_VERIFY_FAIL);
                        showTopicStatus();
                        //setResult(RESULT_OK, new Intent().putExtra(Constant.EXTRA_INFO_TOPIC, topic));
                        onTopicDataChange();
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        Log.e(TAG, "onFailure: " + t.getMessage());
                    }
                });
    }

    /**
     * 联系客服
     */
    void contactCustomerService() {
        progressBar.setVisibility(View.VISIBLE);
        RetrofitManager.getInstance().createRequest(UserService.class)
                .customerService()
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        progressBar.setVisibility(View.GONE);
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "onResponse: " + response.message());
                            showToast(tv_customerService, getString(R.string.system_busy));
                            return;
                        }
                        if (result.isError()) {
                            Log.d(TAG, "onResponse: " + result.getMsg());
                            return;
                        }

                        JSONObject object = (JSONObject) result.getData();
                        //把用户作为临时联系人 保存在数据库
                        User manualUser = object.toJavaObject(User.class);
                        manualUser.setType(Constant.USER_TYPE_TEMP);
                        DBManager.getInstance().getDaoSession().getUserDao().insertOrReplace(manualUser);
                        ChatActivity.startActivity(VerifyTopicActivity.this, manualUser);

                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        progressBar.setVisibility(View.GONE);
                        Log.e(TAG, "onFailure: " + t.getMessage());
                        showToast(tv_customerService, getString(R.string.system_busy));
                    }
                });
    }

    private void onTopicDataChange() {
        notify.setExtraData(JSONObject.toJSONString(topic));
        SystemNotifyConversation notifyConversation = IMSClientBootstrap.getInstance().getConversationService().getNotifyConversation(Constant.CONVERSATION_TYPE_SYSTEM);
        notifyConversation.messageChange(notify);
        DBManager.getInstance().getDaoSession().getMessageDao().update(notify);
    }
}
